package com.mooc.lib_common.mvvm

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.BarUtils
import com.mooc.lib_base_application.BaseApplication
import java.lang.reflect.ParameterizedType

abstract class BaseActivity<VM : ViewModel, V : ViewDataBinding> : AppCompatActivity(){

    protected lateinit var vm : VM
    protected lateinit var v : V

    @SuppressLint("ResourceAsColor")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BaseApplication.instance!!.ref.watch(this)
        v = DataBindingUtil.setContentView(this, bindLayout())
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
        }
        BarUtils.addMarginTopEqualStatusBarHeight(v.root)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        initViewModel()
        initView()
        initData()
    }

    //创建ViewModel对象
    fun initViewModel(){
        val parameterizedType = this.javaClass.genericSuperclass as ParameterizedType
        val types = parameterizedType.actualTypeArguments
        val clazz : Class<VM> = types[0] as Class<VM>
        vm = ViewModelProvider(this,
                ViewModelProvider.NewInstanceFactory()).get(clazz)
    }

    //初始化控件
    abstract fun initView()
    //创建databinding对象
    abstract fun bindLayout():Int
    //初始化数据
    abstract fun initData()

    override fun onDestroy() {
        super.onDestroy()
        v.unbind()
    }

}